import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import articleService from '@/services/articleService'
import { useAppStore } from './app'

export const useBrowseStore = defineStore('browse', () => {
  const appStore = useAppStore()
  
  // 状态数据
  const chapters = ref([])
  const currentChapterArticles = ref([])
  const loading = ref(false)
  const error = ref(null)
  const currentPart = ref('')
  const currentChapter = ref(null)
  const articlesLoading = ref(false)
  
  // 分页状态
  const currentPage = ref(1)
  const perPage = ref(20)
  const totalArticles = ref(0)
  const totalPages = ref(0)
  
  // 搜索和筛选
  const searchQuery = ref('')
  const selectedPart = ref('')
  
  // 计算属性
  const groupedChapters = computed(() => {
    const groups = {}
    chapters.value.forEach(chapter => {
      if (!groups[chapter.part]) {
        groups[chapter.part] = []
      }
      groups[chapter.part].push(chapter)
    })
    return groups
  })
  
  const filteredChapters = computed(() => {
    if (!selectedPart.value) return groupedChapters.value
    return {
      [selectedPart.value]: groupedChapters.value[selectedPart.value] || []
    }
  })
  
  const partNames = computed(() => {
    return Object.keys(groupedChapters.value).sort()
  })
  
  const currentChapterInfo = computed(() => {
    if (!currentPart.value || !currentChapter.value) return null
    return chapters.value.find(
      chapter => chapter.part === currentPart.value && chapter.chapter_number === currentChapter.value
    )
  })
  
  // 操作方法
  async function loadChapters() {
    loading.value = true
    error.value = null
    
    try {
      const response = await articleService.getArticles()
      chapters.value = response.chapters || []
    } catch (err) {
      error.value = err.message
      appStore.setError('获取章节列表失败', err)
    } finally {
      loading.value = false
    }
  }
  
  async function loadChapterArticles(part, chapterNumber, page = 1) {
    articlesLoading.value = true
    error.value = null
    
    try {
      const response = await articleService.getArticlesByChapter(
        part, 
        chapterNumber, 
        { page, per_page: perPage.value }
      )
      
      currentChapterArticles.value = response.articles || []
      totalArticles.value = response.pagination?.total || 0
      totalPages.value = response.pagination?.pages || 0
      currentPage.value = page
      currentPart.value = part
      currentChapter.value = chapterNumber
    } catch (err) {
      error.value = err.message
      appStore.setError('获取条文列表失败', err)
      currentChapterArticles.value = []
    } finally {
      articlesLoading.value = false
    }
  }
  
  function setSelectedPart(part) {
    selectedPart.value = part
  }
  
  function setSearchQuery(query) {
    searchQuery.value = query
  }
  
  function clearCurrentChapter() {
    currentChapterArticles.value = []
    currentPart.value = ''
    currentChapter.value = null
    currentPage.value = 1
  }
  
  async function loadNextPage() {
    if (currentPage.value < totalPages.value && currentPart.value && currentChapter.value) {
      await loadChapterArticles(currentPart.value, currentChapter.value, currentPage.value + 1)
    }
  }
  
  async function loadPreviousPage() {
    if (currentPage.value > 1 && currentPart.value && currentChapter.value) {
      await loadChapterArticles(currentPart.value, currentChapter.value, currentPage.value - 1)
    }
  }
  
  async function goToPage(page) {
    if (page >= 1 && page <= totalPages.value && currentPart.value && currentChapter.value) {
      await loadChapterArticles(currentPart.value, currentChapter.value, page)
    }
  }
  
  function reset() {
    chapters.value = []
    currentChapterArticles.value = []
    loading.value = false
    articlesLoading.value = false
    error.value = null
    currentPart.value = ''
    currentChapter.value = null
    currentPage.value = 1
    totalArticles.value = 0
    totalPages.value = 0
    searchQuery.value = ''
    selectedPart.value = ''
  }
  
  return {
    // 状态
    chapters,
    currentChapterArticles,
    loading,
    articlesLoading,
    error,
    currentPart,
    currentChapter,
    currentPage,
    perPage,
    totalArticles,
    totalPages,
    searchQuery,
    selectedPart,
    
    // 计算属性
    groupedChapters,
    filteredChapters,
    partNames,
    currentChapterInfo,
    
    // 方法
    loadChapters,
    loadChapterArticles,
    setSelectedPart,
    setSearchQuery,
    clearCurrentChapter,
    loadNextPage,
    loadPreviousPage,
    goToPage,
    reset
  }
})
